package org.exeed.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.exeed.constant.TimeConstants;
import org.exeed.dao.UserMapper;
import org.exeed.dto.ModifyTO;
import org.exeed.dto.TokenTO;
import org.exeed.entity.UserEntity;
import org.exeed.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public TokenTO signIn(String username, String password) throws Exception {

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        UserEntity user = userMapper.selectOne(queryWrapper);
        if (user != null && user.getPwd().equals(password)) {

            Map<String, Object> payLoad = new JSONObject(true);
            payLoad.put("userId", user.getId());
            payLoad.put("username", user.getUsername());

            String token = createToken(user.getId() + "", payLoad, TimeConstants.SECONDS_IN_DAY);
            String refreshToken = createToken(user.getId() + "", payLoad, TimeConstants.SECONDS_IN_MONTH);


            Long tokenExpired = JWTUtils.getExpired(token);
            user.setToken(token);
            user.setRefreshToken(refreshToken);
            user.setSignInTime(DateUtil.current());

            userMapper.updateById(user);

            TokenTO tokenTO = new TokenTO();
            tokenTO.setToken(token);
            tokenTO.setRefreshToken(refreshToken);
            tokenTO.setExpiredTime(JWTUtils.getExpired(token));
            return tokenTO;
        }

        return null;

    }

    public boolean modifyPwd(ModifyTO modifyTO){

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", modifyTO.getUsername());

        UserEntity user = userMapper.selectOne(queryWrapper);
        if (user != null && user.getPwd().equals(modifyTO.getOldPwd())) {

            user.setPwd(modifyTO.getNewPwd());
            user.setToken("-");
            user.setRefreshToken("-");

            userMapper.updateById(user);
            return true;
        }
        return false;
    }


    public String createToken(String uuid, Map<String, Object> payload, Long expired) throws Exception {
        return JWTUtils.createJWT(uuid, payload, expired);
    }

    public UserEntity check(String token) {

        Long now = DateUtil.current();

        Long expired = JWTUtils.getExpired(token);

        if (now > expired) {
            return null;
        }


        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token", token);

        UserEntity user = userMapper.selectOne(queryWrapper);

        return user;
    }

}
